package utils

import (
	"fmt"
	"os/exec"
	"path/filepath"
	"strings"
)

// CommandExecutor 命令执行接口
type CommandExecutor interface {
	RunCommand(name string, args ...string) error
	RunCommandWithOutput(name string, args ...string) (string, error)
	RunEtcdCtl(action string, args ...string) error
}

// DefaultExecutor 默认命令执行器
type DefaultExecutor struct {
	env map[string]string
}

// NewCommandExecutor 创建默认命令执行器实例
func NewCommandExecutor(env map[string]string) *DefaultExecutor {
	return &DefaultExecutor{
		env: env,
	}
}

// RunCommand 执行命令
func (e *DefaultExecutor) RunCommand(name string, args ...string) error {
	cmd := exec.Command(name, args...)
	output, err := cmd.CombinedOutput()
	fmt.Printf("执行命令: %s %v\n输出:\n%s\n", name, args, string(output))
	return err
}

func (e *DefaultExecutor) RunCommandWithOutput(name string, args ...string) (string, error) {
	cmd := exec.Command(name, args...)
	output, err := cmd.CombinedOutput()
	fmt.Printf("执行命令: %s %v\n输出:\n%s\n", name, args, string(output))
	if err != nil {
		return "", fmt.Errorf("执行命令失败: %v, 输出: %s", err, string(output))
	}
	return strings.TrimSpace(string(output)), nil
}

// RunEtcdCtl 执行 etcdctl 命令
func (e *DefaultExecutor) RunEtcdCtl(action string, args ...string) error {
	// 使用配置的数据目录
	etcdPKIPath := filepath.Join(e.env["SEALOS_DATA_ROOT"], "pki/etcd")

	cmd := exec.Command("etcdctl", append([]string{
		"--endpoints=https://127.0.0.1:2379",
		fmt.Sprintf("--cacert=%s/ca.crt", etcdPKIPath),
		fmt.Sprintf("--cert=%s/server.crt", etcdPKIPath),
		fmt.Sprintf("--key=%s/server.key", etcdPKIPath),
		action,
	}, args...)...)

	output, err := cmd.CombinedOutput()
	fmt.Printf("执行 etcdctl 命令: %s\n输出:\n%s\n", action, string(output))
	if err != nil {
		return fmt.Errorf("执行 etcdctl 命令失败: %v, 输出: %s", err, string(output))
	}
	return nil
}
